//
//  IMMessageManager.m
//  markmap
//
//  Created by 甘世清 on 2024/5/27.
//

#import "IMMessageManager.h"
#import "PeopleDetaileModel.h"
#import "IMMapViewController.h"
#import "IMtextMessageTableViewCell.h"
#import "IMImageMessageTableViewCell.h"
#import "IMMessageViewController.h"
#import "IMMapMessageTableViewCell.h"
#import "IMJinDouMessageTableViewCell.h"
#import "IMPopTopView.h"
@interface IMMessageManager ()

@property (nonatomic,copy)NSString *roomId;

@end
@implementation IMMessageManager

+(IMMessageManager *)sharedIMManager {//单例 实例化方法
   static IMMessageManager *imManager;
   @synchronized(self) {
       if (!imManager)
           imManager = [[self alloc] init];
   }
   return imManager;
}
/// 根据类型进行操作
/// - Parameters:
///   - model: 房间模型
///   - type: 类型 0 相册 1相机 2定位 3礼物
-(void)SQ_sendMsg:(IMListModel*)model type:(NSInteger)type{
    [IMMessageManager sharedIMManager].roomId = model.roomId;
    if (type == 0) {
        TZImagePickerController * vc = [[TZImagePickerController alloc]init];
        vc.maxImagesCount = 9;
        vc.allowPickingVideo = NO;
        vc.sortAscendingByModificationDate = NO;
        vc.modalPresentationStyle = UIModalPresentationFullScreen;
        [[Manager SQ_getCurrentViewController] presentViewController:vc animated:YES completion:nil];
        [vc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
            for (UIImage * image in photos ) {
              [[IMMessageManager sharedIMManager]SQ_sendImage:image roomID:model.roomId];
            }
        }];
    } else if (type == 1) {
        UIImagePickerController * imagePickerVc = [[UIImagePickerController alloc] init];
        imagePickerVc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;

        imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
        imagePickerVc.delegate = self;
//        imagePickerVc.allowsEditing = YES;
        imagePickerVc.videoQuality = UIImagePickerControllerQualityTypeHigh;
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([UIImagePickerController isSourceTypeAvailable: sourceType]) {
            imagePickerVc.sourceType = sourceType;
            [[Manager SQ_getCurrentViewController] presentViewController:imagePickerVc animated:YES completion:NULL];
        }
    }else if (type == 2){
        IMMapViewController * vc = [[IMMapViewController alloc]init];
        vc.modalPresentationStyle = UIModalPresentationFullScreen;
        vc.model = model;
        [[Manager SQ_getCurrentViewController] presentViewController:vc animated:YES completion:nil];
    }
}
-(void)SQ_sendImage:(UIImage*)image roomID:(NSString*)roomID{
    [HttpTool SQ_Image:image successBlock:^(BaseModel * _Nonnull httpModel) {
        NSString * imageurl = httpModel.data;
        UIImageView * imageView = [[UIImageView alloc]init];
        [imageView sd_setImageWithURL:SQURLImage(imageurl)];
        
        NSString * imageW = [NSString stringWithFormat:@"%.f",image.size.width];
        NSString * imageH = [NSString stringWithFormat:@"%.f",image.size.height];
        NSMutableDictionary * ext = [[NSMutableDictionary alloc]init];
        [ext setObject:imageurl forKey:@"url"];
        [ext setObject:imageW forKey:@"imageW"];
        [ext setObject:imageH forKey:@"imageH"];
        [ext setObject:[UserModel share].name forKey:@"name"];
        [ext setObject:[UserModel share].portrait forKey:@"portrait"];
        [ext setObject:[UserModel share].userid forKey:@"peopleId"];

        NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
        [dic setObject:imageurl forKey:@"content"];
        [dic setObject:[ext mj_JSONString] forKey:@"ext"];
        [dic setObject:@"200" forKey:@"order"];
        [dic setObject:@"1" forKey:@"msgType"];
        [dic setObject:roomID forKey:@"roomId"];
        [[SQWebSocket shareManager]SQ_send:[dic mj_JSONString] isSend:^(BOOL isSend) {
            if (isSend) { //发送成功就刷新ui
                DTLog(@"图片发送成功");
            } else {//发送失败就提示
                [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"发送失败,请检查网络!")];
            }
        }];
       
      } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
            
    }];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
   
     if ([type isEqualToString:@"public.image"]) {
            UIImage *photo = [info objectForKey:UIImagePickerControllerOriginalImage];
         if(photo.imageOrientation!=UIImageOrientationUp){
                     // Adjust picture Angle
            UIGraphicsBeginImageContext(photo.size);
            [photo drawInRect:CGRectMake(0, 0, photo.size.width, photo.size.height)];
            photo = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            }
         [[IMMessageManager sharedIMManager]SQ_sendImage:photo roomID:[IMMessageManager sharedIMManager].roomId];
    }else{
        [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"Please select photo") ];
    }
}

/// 读取所有
/// - Parameter model: 房间模型
-(void)SQ_readAll:(IMListModel*)model{
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [dic setObject:@"204" forKey:@"order"];
    [dic setObject:model.roomId forKey:@"roomId"];
    [[SQWebSocket shareManager]SQ_send:[dic mj_JSONString] isSend:^(BOOL isSend) {
       //全部已读成功 减少未读数
        if (isSend) {
            IMListModel * mo = [SQFMDBManager SQ_roomIDGetIMListModel:model.roomId];
            mo.noReadCount = 0;
            [SQFMDBManager SQ_addListIM:mo];
        }
    }];
}
/// 给模型二次改造
/// - Parameters:
///   - indexPath: 当前index
///   - jsonArray: 数组
-(IMMessageModel*)SQ_SetUPModel:(NSIndexPath*)indexPath array:(NSMutableArray*)jsonArray{
    IMMessageModel * model = [jsonArray objectAtIndex:indexPath.item];
    //判断当前是否显示时间
    if (indexPath.item ==0) {
        //如果是第一个直接显示
        model.isShowTime = YES;
    }else{
        IMMessageModel * oldModel = [jsonArray objectAtIndex:indexPath.item-1];
        if ([oldModel.time isNotEmpty]&&[model.time isNotEmpty]) {
            int time = [model.time intValue];
            int timeold = [oldModel.time intValue];
            if (time-timeold >= 300) {
                model.isShowTime = YES; //如果两个im之间超过5分钟
            } else {
                model.isShowTime = NO; //如果两个im之间不超过5分钟
            }
        } else {
            model.isShowTime = YES; //如果有时间为空,直接显示
        }
    }
    return model;
}

/// 根据类型判断哪个cell
/// - Parameters:
///   - model: model description
///   - tableView: tableView description
///   - indexPath: indexPath description
+(BaseIMTableViewCell*)SQ_getCell:(IMMessageModel*)model table:(UITableView*)tableView indexPath:(NSIndexPath*)indexPath{
   
    if (model.msgType == 0) {
        IMtextMessageTableViewCell * cell0 = [tableView dequeueReusableCellWithIdentifier:model.cellIndentify forIndexPath:indexPath];
        // 给cell赋值
        [cell0 setModel:model];
        cell0.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell0;
    } else if (model.msgType == 1) {
        IMImageMessageTableViewCell * cell1 = [tableView dequeueReusableCellWithIdentifier:model.cellIndentify forIndexPath:indexPath];
        // 给cell赋值
        [cell1 setModel:model];
        cell1.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell1;
    } else if (model.msgType == 5) {
        IMMapMessageTableViewCell * cell5 = [tableView dequeueReusableCellWithIdentifier:model.cellIndentify forIndexPath:indexPath];
        // 给cell赋值
        [cell5 setModel:model];
        cell5.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell5;
    } else if (model.msgType == 10) {
        IMJinDouMessageTableViewCell * cell10 = [tableView dequeueReusableCellWithIdentifier:model.cellIndentify forIndexPath:indexPath];
        // 给cell赋值
        [cell10 setModel:model];
        cell10.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell10;
    }
    BaseIMTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:model.cellIndentify forIndexPath:indexPath];
    [cell setModel:model];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

/// 获取cell高度
/// - Parameter model: cell对应的模型
+(float)SQ_getCellHeight:(IMMessageModel*)model{
    float h = 10;
    float textH = 0;
    if (model.msgType == 0) {
        textH  = 10;
    }
    if (model.isShowTime) {
        h = 40;
    }
   
    return  model.cellSize.height + h + textH;
}

/// cell点击事件
/// - Parameters:
///   - tableView: tableView
///   - indexPath: index
-(void)SQ_celldidSelecttable:(UITableView*)tableView indexPath:(NSIndexPath*)indexPath array:(NSMutableArray*)jsonArray{
  
    NSMutableArray * dataArray = [[NSMutableArray alloc]init];
   __block NSInteger index = 0;
    IMMessageModel * mo = [jsonArray objectAtIndex:indexPath.item];
    [jsonArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        IMMessageModel * model = (IMMessageModel*)obj;
        if (model.msgType ==1) {
            IMImageMessageTableViewCell * cell1 = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForItem:idx inSection:0]];
          GKPhoto *photo = [GKPhoto new];
          photo.url = SQURLImage(model.content);
          photo.sourceImageView = cell1.imImageView;
          [dataArray addObject:photo];
            if ([model.IMId isEqualToString: mo.IMId]) {
                index = dataArray.count - 1;
            }
        }  
    }];
    GKPhotoBrowser *browser = [GKPhotoBrowser photoBrowserWithPhotos:dataArray currentIndex:index];
    [browser showFromVC:[Manager SQ_getCurrentViewController]];
}

/// 顶部显示聊天内容
/// - Parameter model: 聊天数据
+(void)SQ_showMessage:(IMMessageModel*)model{
    
    if (![UserModel share].isPush) {
        return;
    }
    if ([model.time isNotEmpty]) {
        int timeold = [model.time intValue];
        int time = [[NSString SQ_currentTime] intValue];
        if (time - timeold > 60) {
            return; //超过1分钟的消息不提示
        }
    }
    UIViewController * vc = [Manager SQ_getCurrentViewController];
    if ([vc isKindOfClass:[IMMessageViewController class]]) {
        return;
    } 
    
    IMPopTopView * btn = [[IMPopTopView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDETH-40, 64)];
    btn.model = model;

    LSTPopView * pop = [LSTPopView initWithCustomView:btn
                                             parentView:nil
                                               popStyle:LSTPopStyleSmoothFromTop dismissStyle:LSTDismissStyleSmoothToTop];
    pop.hemStyle = LSTHemStyleTop;
    pop.isStack = YES;
    pop.isHideBg = YES;
    pop.adjustY = TopHeight-40;
    pop.showTime = 2;
    [pop pop];
}
 
@end
